package com.ymk.cmd;

import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.user.UserInfoBO;
import com.ymk.core.code.cmd.UserCmdCode;
import com.ymk.core.constants.WxConstants;
import com.ymk.service.IUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class UserPatchCmd extends ACmd {

    @Override
    public CmdSign executeMop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("userId", reqData.getUserId())
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());
        if(Objects.isNull(respData)){
            throw new MallException("用户不存在");
        }
        reqData.setId(respData.getId());
        this.userService.update(reqData);

        return respSign;
    }
    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("userId", reqData.getUserId())
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());
        if(Objects.isNull(respData)){
            throw new MallException("用户不存在");
        }
        reqData.setId(respData.getId());
        this.userService.update(reqData);

        return respSign;
    }

    @Override
    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);
        String openId = request.getHeader(WxConstants.X_WX_OPENID);
        if (StringUtils.isBlank(openId)) {
            throw new MallException("请求异常,header未发现openID");
        }
        if(StringUtils.isBlank(reqData.getUserId())){
            throw new MallException("userId不能为空");
        }
        return null;
    }
    @Override
    public boolean anon(CmdSign sign) {
        return true;
    }
    @Override
    public String getCmdCode() {
        return UserCmdCode.USER_PATCH;
    }

    @Autowired
    private IUserInfoService userService;
}